package com.xunfang.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xunfang.bean.Building;
import com.xunfang.bean.House;
import com.xunfang.bean.Result;
import com.xunfang.exception.MyDeleteException;
import com.xunfang.mapper.BuildingMapper;
import com.xunfang.mapper.HouseMapper;
import com.xunfang.service.BuildingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author yellow Doctor
 * @date 2025-09-12
 * @desc https://blog.csdn.net/hekai7217
 */
@Service
public class BuildingServiceImpl implements BuildingService {

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private HouseMapper houseMapper;

    @Override
    public Result addBuild(Building building) {
        return buildingMapper.addBuild(building) > 0 ? Result.ok() : Result.fail();
    }

    @Override
    public Result deleteBuild(int id) {

        //判断 house中是否有楼栋数据使用
        //如果有抛出异常
        //全局中来处理这个异常 不让删除数据
        List<House> houses = houseMapper.selectHousesByBuildingId(id);

        if (!CollectionUtils.isEmpty(houses)){
            throw new MyDeleteException("楼栋数据有人在住,不能删除...");
        }

        return buildingMapper.deleteBuild(id) > 0 ? Result.ok() : Result.fail();
    }

    @Override
    public Result batchBuild(List<Integer> ids) {
        return buildingMapper.batchBuild(ids) > 0 ? Result.ok() : Result.fail();
    }

    @Override
    public Result updateBuild(Building building) {
        return buildingMapper.updateBuild(building) > 0 ? Result.ok() : Result.fail();
    }

    @Override
    public Result<PageInfo> selectAllBuilding(Integer currentPage,Integer pageSize) {

        //01 分页
        PageHelper.startPage(currentPage,pageSize);
        //02 查询所有
        List<Building> list = buildingMapper.selectAllBuilding();

        //03 组装 PageInfo 对象

        /**
         *  page info 说明
         *     page.getList();   分页数据的集合
         *     page.getTotal();  分页总数
         */
        PageInfo<Building> page = new PageInfo(list);
        List<Building> list1 = page.getList();
        long total = page.getTotal();

        //04 返回数据

        return Result.ok(page);
    }
}
